package com.example.roomwordssample;


import android.content.Context;
import android.os.AsyncTask;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;


@Database(entities = {Word.class},version = 1,exportSchema = false)
public abstract class WordRoomDatabase extends RoomDatabase{
    public abstract WordDao wordDao();

    private static WordRoomDatabase INSTANCE;

    private static RoomDatabase.Callback callback=new RoomDatabase.Callback(){
        @Override
        public void onOpen( SupportSQLiteDatabase db) {
            super.onOpen(db);
            new PopulateDbAsync(INSTANCE).execute();
        }
    };
    private static class PopulateDbAsync extends AsyncTask<Void,Void,Void>{
        private final WordDao dao;
        String [] words={"word","PopulateDbAsync","AsyncTask"};

        private PopulateDbAsync(WordRoomDatabase db){
            this.dao= db.wordDao();
        }
        @Override
        protected Void doInBackground(Void... voids){
            dao.deleteAll();
            for (int i = 0; i < words.length; i++) {
                dao.insert(new Word(words[i]));
            }
            return  null;
        }
    }

    static WordRoomDatabase getDatabase(final Context context){
        if (INSTANCE==null){
            synchronized (WordRoomDatabase.class){
                if (INSTANCE==null){
                    INSTANCE= Room.databaseBuilder(context.getApplicationContext(),
                            WordRoomDatabase.class,"word_database")
                            .fallbackToDestructiveMigration()
                            .addCallback(callback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

}
